#include<iostream>
#include"../include/Tcpserver.h"
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
using namespace std;
void Tcpserver::init(int port)
{
		lfd=socket(AF_INET,SOCK_STREAM,0);
		if(lfd==-1)
		{
			cout<<"套接字创建失败"<<endl;
			return ;
		}
		int opt=1;
		setsockopt(lfd,SOL_SOCKET,SO_REUSEADDR,(const void *)&opt,sizeof(opt));
		struct sockaddr_in serv_addr;
		memset(&serv_addr,0,sizeof(serv_addr));
		serv_addr.sin_family=AF_INET;
		serv_addr.sin_port=htons(port);
		serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
		int ret=bind(lfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
		if(ret==-1)
		{
			cout<<"绑定失败"<<endl;
			return;
		}
		ret=listen(lfd,64);
		if(ret==-1)
		{
			cout<<"监听失败"<<endl;
			return;
		}
}
int Tcpserver::wait_user()
{
		struct sockaddr_in client_addr;
		socklen_t client_len=sizeof(client_addr);
		cfd=accept(lfd,(struct sockaddr*)&client_addr,&client_len);
		if(cfd==-1)
		{
			cout<<"连接失败"<<endl;
			return -1;
		}
		else
		{
			cout<<"lianjie"<<endl;
			return 0;
		}
}
string Tcpserver::back_message()
{
		string data;
		for(;;)
		{
			char buf[1024]={0};
			int len=recv(cfd,buf,1024,0);
			if(len==-1)
			{
				close(cfd);
				cout<<"连接断开"<<endl;
				break;
			}
			if(len>0)
			{
				
				data=buf;
				cout<<data<<endl;
				return data;
			}
			if(len==0)
			{
				close(cfd);
				cout<<"连接断开"<<endl;
				break;
			}
		}
		return "";
}
